# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  include Session
  
  layout "two_columns"
  
  helper :all
  
  before_filter :check_user_logged, 
                :redirect_if_not_active, 
                :set_locale,
                :set_time_zone
  
  helper_method :current_user, 
                :user_logged?
  
  def authorized?
    if current_user.admin_actions.include? "#{controller_name}_#{action_name}"
      unless current_user.designations.find_by_project_id(@project.id).admin?
        flash[:notice] = I18n.t :dont_have_permission, :scope => :permission
        redirect_to :back
      end
    end
  end
  
  def project_will_be_deleted?
    if @project.delete_at
      flash.now[:warning] = I18n.t(:marked_for_deletion, :date => @template.distance_of_time_in_words(Time.now, @project.delete_at), :scope => [:project, :messages])
      
      if Time.now > @project.delete_at
        @project.destroy and redirect_to root_path
      end
    end
  end
  
  def get_project
    begin
      @project = current_user.projects.find(params[:project_id])
    rescue
      flash[:notice] = I18n.t :dont_have_permission, :scope => :permission
      redirect_to root_path
    end
  end
  
  def set_locale
    default_locale = :pt
    
    if user_logged?
      locale = current_user.locale
    else
      locale = request.env['HTTP_ACCEPT_LANGUAGE'].nil? ? nil : request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
    end
    
    begin
      I18n.locale = locale
    rescue
      I18n.locale = default_locale
    end
  end
  
  def set_time_zone
    Time.zone = current_user.timezone unless current_user.timezone.nil?
  end
  
  def redirect_if_not_active
    redirect_to edit_user_url(current_user) if current_user.password.blank?
  end
end